package day16.tarena.GUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
 * @author Peihu.Wang
 */
public class Calculator implements ActionListener {
	private boolean append =false;
	
	JTextField jt = new JTextField(0);
	private String op1 ="0";
	private String operator ="+";
	public void actionPerformed(ActionEvent e) {
		String comm = e.getActionCommand();
			if("0123456789".indexOf(comm) != -1){
				if(append){
					String temp = jt.getText();
					jt.setText(temp+comm);
				}else {
					jt.setText(comm);
					append =true;
				}
			}else if("+-*/".indexOf(comm) != -1){
				op1 = jt.getText();
				operator = comm;
				append  = false;
			}else if("=".equals(comm)){
				String op2 =jt.getText();
				double d1 = Double.parseDouble(op1);
				double d2 = Double.parseDouble(op2);
				if("+".equals(operator)){
					d1 = d1 + d2;
				}else if("-".equals(operator)){
					d1 = d1 - d2;
				}else	if("*".equals(operator)){
					d1 = d1 * d2;
				}else{
					d1 = d1 / d2;
				}
				jt.setText(d1+"");
			}else if(".".equals(comm)){
				String temp = jt.getText();		 // Get number from  JTextField
				if(temp.indexOf(".") ==-1){
					jt.setText(temp+".");
					append = true;
				}
			}else if("CE".indexOf(comm) !=-1){
				jt.setText("0");
				append  = false;
			}else if("+/-".equals(comm)){
				String temp = jt.getText();  		 // Get number from  JTextField
				if(temp.startsWith("-")){
					jt.setText(temp.substring(1));
				}else{
					jt.setText("-"+temp);
				} 
			}else if("BackS".equals(comm)){
				String temp = jt.getText();
				if(temp.length()>0){
					jt.setText(temp.substring(0,temp.length()-1));
				}
			}
	}

	public Calculator(){
		JFrame jf = new JFrame("Calculator");
		jf.add(jt,BorderLayout.NORTH);
		JPanel jp = new JPanel();
		jt.setEditable(false);
		GridLayout gl = new GridLayout(5,4);
		String[] lab = {"BackS","CE","C","+",
							"7","8","9","-",
							"4","5","6","*",
							"1","2","3","/",
							"0","+/-",".","="};
		jp.setLayout(gl);
		for(int i=0;i<lab.length;i++){
			JButton jb = new JButton(lab[i]);
			jb.addActionListener(this);		//注册
			jp.add(jb);
		}
		jf.add(jp);
		jf.setLocation(300,200);			//设置出现位置
		jf.pack();
		jf.setResizable(false);//设置窗口大小不可改变
		jf.setVisible(true);//设置可见
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
	
	public static void main(String[] args) {
		new Calculator();
	}
}
